package com.example.medicalapp.network;

import android.util.Log;

import com.example.medicalapp.activity.PatientDetailActivity;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class DeepSeekService {
    private static final String TAG = "DeepSeekService";
    private static final String BASE_URL = "https://api.deepseek.com/";
    private static final String API_KEY = "sk-d5fa25a1df2a44548741be6b0f58569e";
    private static final String MODEL = "deepseek-chat";
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    private final OkHttpClient client;
    private final PatientDetailActivity activity; // 声明为final
    private Call currentCall;
    private final Gson gson;

    public DeepSeekService(PatientDetailActivity activity) {
        this.activity = activity; // 构造函数中赋值一次，满足effectively final
        this.gson = new Gson();
        this.client = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .build();
    }

    public void sendDiagnosisRequest(String symptoms) {
        cancelCurrentRequest();

        // 创建局部final变量引用activity
        final PatientDetailActivity finalActivity = this.activity;

        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", MODEL);

        Map<String, String> message = new HashMap<>();
        message.put("role", "user");
        message.put("content", "请作为专业医生，根据以下症状进行医学诊断：" + symptoms +
                "。请给出详细诊断结果、可能的病因分析和建议处方，用中文详细回答。");

        requestBody.put("messages", new Object[]{message});
        requestBody.put("stream", true);
        requestBody.put("temperature", 0.7);

        String jsonBody = gson.toJson(requestBody);

        Request request = new Request.Builder()
                .url(BASE_URL + "v1/chat/completions")
                .addHeader("Content-Type", "application/json")
                .addHeader("Authorization", "Bearer " + API_KEY)
                .post(RequestBody.create(jsonBody, JSON))
                .build();

        currentCall = client.newCall(request);
        currentCall.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (call.isCanceled()) {
                    Log.d(TAG, "Request canceled by user");
                    return;
                }

                Log.e(TAG, "API请求失败: " + e.getMessage(), e);
                // 使用局部final变量
                final PatientDetailActivity callbackActivity = finalActivity;
                callbackActivity.runOnUiThread(() -> {
                    String errorMsg = "AI诊断失败: ";
                    if (e instanceof java.net.SocketTimeoutException) {
                        errorMsg += "请求超时，请重试";
                    } else if (e instanceof java.net.UnknownHostException) {
                        errorMsg += "无法连接到服务器，请检查网络";
                    } else if (e instanceof java.net.ConnectException) {
                        errorMsg += "连接失败，请检查网络";
                    } else {
                        errorMsg += "未知错误，请稍后重试";
                    }
                    callbackActivity.updateAiProcess(errorMsg);
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // 创建回调内的final变量
                final PatientDetailActivity responseActivity = finalActivity;
                try {
                    if (!response.isSuccessful()) {
                        String errorMsg = "AI诊断失败，错误代码: " + response.code();
                        if (response.body() != null) {
                            String errorBody = response.body().string();
                            Log.e(TAG, "API错误响应: " + errorBody);
                            try {
                                JsonObject errorJson = gson.fromJson(errorBody, JsonObject.class);
                                if (errorJson.has("error") && errorJson.get("error").isJsonObject()) {
                                    String message = errorJson.getAsJsonObject("error").get("message").getAsString();
                                    errorMsg += "，" + message;
                                }
                            } catch (Exception e) {
                                Log.e(TAG, "解析错误响应失败", e);
                            }
                        }
                        Log.e(TAG, errorMsg);
                        final String finalErrorMsg = errorMsg;
                        responseActivity.runOnUiThread(() -> responseActivity.updateAiProcess(finalErrorMsg));
                        return;
                    }

                    ResponseBody body = response.body();
                    if (body == null) {
                        Log.e(TAG, "API响应体为空");
                        responseActivity.runOnUiThread(() ->
                                responseActivity.updateAiProcess("AI诊断失败：未获取到响应内容"));
                        return;
                    }

                    processStreamResponse(body, responseActivity);
                } finally {
                    if (response.body() != null) {
                        response.body().close();
                    }
                }
            }
        });
    }

    /**
     * 修改方法参数，直接传递final的activity引用
     */
    private void processStreamResponse(ResponseBody body, final PatientDetailActivity activity) throws IOException {
        try (okio.BufferedSource source = body.source()) {
            while (!source.exhausted() && !Thread.currentThread().isInterrupted()) {
                String line = source.readUtf8Line();
                if (line == null || line.isEmpty()) continue;

                if (line.startsWith("data: ")) {
                    String data = line.substring(6);
                    if (data.equals("[DONE]")) {
                        activity.runOnUiThread(activity::onAiDiagnosisComplete);
                        break;
                    }

                    try {
                        JsonObject jsonObject = gson.fromJson(data, JsonObject.class);
                        if (jsonObject.has("choices") && jsonObject.get("choices").isJsonArray() &&
                                !jsonObject.getAsJsonArray("choices").isEmpty()) {

                            JsonObject choice = jsonObject.getAsJsonArray("choices").get(0).getAsJsonObject();
                            if (choice.has("delta") && choice.get("delta").isJsonObject()) {
                                JsonObject delta = choice.getAsJsonObject("delta");
                                if (delta.has("content")) {
                                    final String content = delta.get("content").getAsString();
                                    activity.runOnUiThread(() -> activity.updateAiProcess(content));
                                }
                            }
                        }
                    } catch (Exception e) {
                        Log.e(TAG, "解析响应失败: " + e.getMessage() + "，响应内容: " + line, e);
                    }
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "处理流式响应失败: " + e.getMessage(), e);
            final String errorMsg = "AI诊断中断：" + e.getMessage();
            activity.runOnUiThread(() -> activity.updateAiProcess(errorMsg));
        }
    }

    public void cancelCurrentRequest() {
        if (currentCall != null && !currentCall.isCanceled() && !currentCall.isExecuted()) {
            currentCall.cancel();
            Log.d(TAG, "Current request canceled");
        }
    }
}
    